package com.example.kafka.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.util.Scanner;

public  class FileUtil {


    /***
     * 获取系统根路径下文件classpath:
     * @param fileName
     * @param tempFilePrefix
     * @param tempFileSuffix
     * @return
     * @throws IOException
     */
    public static File getFileByResource(String fileName, String tempFilePrefix, String tempFileSuffix) throws IOException {

        ClassPathResource classPathResource = new ClassPathResource(fileName);
        InputStream inputStream = classPathResource.getInputStream();
        File file = File.createTempFile(tempFilePrefix, tempFileSuffix);
        try {
            FileUtils.copyInputStreamToFile(inputStream, file);
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
        return file;
    }

    /***
     * 获取配置文件内容
     * @param file
     * @return
     */
    public static String fileReaderByScanner(File file) {
        Scanner scanner = null;
        StringBuilder buffer = new StringBuilder();
        try {
            scanner = new Scanner(file, "utf-8");
            while (scanner.hasNextLine()) {
                buffer.append(scanner.nextLine());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
        return buffer.toString();

    }
}
